package com.ray.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DepartmentBean;
import com.ray.bean.MaterialBean;
import com.ray.bean.OrderInfoTemplateBean;
import com.ray.bean.PersonBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.OrderCreateMapper;
import com.ray.pojo.MyUser;
import com.ray.service.BasicDataService;
import com.ray.service.OrderCreateService;
import com.ray.service.OrderInfoTemplateService;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.UploadFilesUtil;
import com.ray.util.qiniu.QiniuConfig;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * 订单创建数据获取及提交
 * @author Shensg
 * 2018年1月24日
 */

@SuppressWarnings("unused")
@RestController
@RequestMapping("/createOrder")
public class OrderCreateController {
	@Autowired
	OrderCreateService orderCreateService;
	
	@Autowired
	OrderInfoTemplateService orderInfoTemplateService;
	
	//图片上传
	@RequestMapping("/uploadPic")
	public Map queryFile(@RequestParam("file") CommonsMultipartFile files[],HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		//return ResponseUtil.ResponseResult(UploadFilesUtil.loadFileUtils(files,request,"/uploadpic/orderpic"+sdf.format(new Date())));
		return ResponseUtil.ResponseResult(UploadFilesUtil.loadFileByQiniu4BucketShinehaopic(files, request));
	}  
	//图片上传
	@RequestMapping("/uploadPicToLocal")
	public Map uploadPicToLocal(@RequestParam("file") CommonsMultipartFile files[],HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return ResponseUtil.ResponseResult(UploadFilesUtil.loadFileUtils(files,request,"/uploadpic/orderpic"+sdf.format(new Date())));
	} 
	
	//订单信息列表获取
	@RequestMapping("/getOrderTabList")
	public Map getOrderTabList(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.getOrderTabList(map));
	} 
	
	//订单信息列表获取
	@RequestMapping("/getDataBasicList")
	public Map getDataBasicList(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.getDataBasicList(map));
	}
	
	@RequestMapping("/updateDataBasicById")
	public Map updateDataBasicById(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		orderCreateService.updateDataBasicById(map);
        return ResponseUtil.ResponseResult(null);
	}
	
	//获取原料辅料子节点信息
	@RequestMapping("/getFactoryTabChildList")
	public Map getFactoryTabChildList(HttpServletRequest request) throws IOException, ServiceException  {  
		Map<String, String> map=RequestUtil.getRequestAllParam(request);
		// 第三种：推荐，尤其是容量大时
        /*System.out.println("第三种：通过Map.entrySet遍历key和value");
        for (Map.Entry<String, String> entry: map.entrySet()) {
            //Map.entry<Integer,String> 映射项（键-值对）  有几个方法：用上面的名字entry
            //entry.getKey() ;entry.getValue(); entry.setValue();
            //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
            System.out.println("key= " + entry.getKey() + " and value= "
                    + entry.getValue());
        }*/
        List<Map> retmap = orderCreateService.getFactoryTabChildList(map);
        int total = orderCreateService.getFactoryTabChildListTotal(map);
        JSONObject object = new JSONObject();
        object.put("total",total);
        object.put("rows", retmap);
        return ResponseUtil.ResponseResult(object);
	} 
	
	//获取物料表中有的部门
	@RequestMapping("/getCompanyMaterialDeptInfo")
	public Map getCompanyMaterialDeptInfo(HttpServletRequest request) throws IOException, ServiceException  {  
		Map<String, String> map=RequestUtil.getRequestAllParam(request);
	    List<Map> companyMaterialDeptInfoList = orderCreateService.getCompanyMaterialDeptInfo(map);
	    return ResponseUtil.ResponseResult(companyMaterialDeptInfoList);
	}
    
	//保存为订单模板
	@RequestMapping("/saveAsOrderTemplate")
	public Map saveAsOrderTemplate(HttpServletRequest request) throws IOException, ServiceException  {  
		Map<String,String> map=RequestUtil.getRequestAllParam(request);
		OrderInfoTemplateBean bean = new OrderInfoTemplateBean();
		bean.setCompany(map.get("loginCompany"));
		bean.setTempInfo(map.get("temp_info"));
		bean.setTempName(map.get("temp_name"));
		bean.setTableSourceArr(map.get("order_s_table_source_arr"));
		bean.setTableSourceLineTotal(map.get("table_source_line_total"));
		bean.setTableSourceArrStr(map.get("order_s_table_source_arr_str"));
		bean.setTableSourceArrForTwo(map.get("order_s_table_source_arr_for_two"));
		bean.setTableSourceLineTotalForTwo(map.get("table_source_line_total_for_two"));
		bean.setTableSourceArrStrForTwo(map.get("order_s_table_source_arr_str_for_two"));
		bean.setStatus(1);
		bean.setType(Integer.valueOf(map.get("type")));
		orderInfoTemplateService.saveAsOrderTemplate(bean);
        return ResponseUtil.ResponseResult(bean);
	} 
	
	//获取订单模板
	@RequestMapping("/getTemplateById")
	public Map getTemplateById(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		OrderInfoTemplateBean bean = new OrderInfoTemplateBean();
		bean.setId(Integer.valueOf((String)map.get("id")));
		//从缓存中获取
		Object object = RedisCache.getDataFromRedis(RedisKey.ORDER_INFO_TEMPLATE+bean.getId());
		if (object!=null) {
			return ResponseUtil.ResponseResult(object);
		}
		//缓存没有命中 数据库获取
		Map retMap = orderInfoTemplateService.getTemplateById(bean);
		//存入缓存
		RedisCache.setDataToRedis(RedisKey.ORDER_INFO_TEMPLATE+bean.getId(),retMap,RedisKey.ORDER_INFO_TEMPLATE_Expiretime);
        return ResponseUtil.ResponseResult(retMap);
	} 
	//获取订单模板
	@RequestMapping("/getTemplateInfoByOrderNo")
	public Map getTemplateInfoByOrderNo(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		String templateId = orderInfoTemplateService.getTemplateInfoByOrderNo(map).get("template_id").toString();
		//从缓存中获取
		Object object = RedisCache.getDataFromRedis(RedisKey.ORDER_INFO_TEMPLATE+templateId);
		if (object!=null) {
			return ResponseUtil.ResponseResult(object);
		}
		OrderInfoTemplateBean bean = new OrderInfoTemplateBean();
		bean.setId(Integer.valueOf(templateId));
		//缓存没有命中 数据库获取
		Map retMap = orderInfoTemplateService.getTemplateById(bean);
		return ResponseUtil.ResponseResult(retMap);
	} 
	//获取订单模板列表
	@RequestMapping("/getTempList")
	public Map getTempList(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		List<Map<String, String>> retmap = orderInfoTemplateService.getTempList(map);
		JSONObject object = new JSONObject();
        object.put("total",retmap.size());
        object.put("rows", retmap);
        return ResponseUtil.ResponseResult(object);
	} 
	//获取订单信息固定值
	@RequestMapping("/getOrderInfoFixed")
	public Map getOrderInfoFixed(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		List<Map<String, String>> list = new ArrayList<>();
		list.add(0, orderCreateService.getOrderInfoFixed(map));
		list.add(1, map);
		list.add(2, orderCreateService.getOrderInfoFixedPermission(map));
        return ResponseUtil.ResponseResult(list);
	} 
	
	//保存订单信息
	@RequestMapping("/saveOrderInfo")
	public Map saveOrderInfo(HttpServletRequest request) throws IOException  {  
		Map<String, Object> map=RequestUtil.getRequestAllParam(request);
		String save_as_new_order=map.get("save_as_new_order").toString();
		int audit_total = orderCreateService.getAuditTotalByOrderNo(map);
		if(audit_total>0&&!"1".equals(save_as_new_order)) {
			//删除原来的模版
			orderCreateService.deleteTemplate(map);
			return ResponseUtil.ResponseError("此订单已审核，禁止修改！");
		}
		boolean isSave = orderCreateService.saveOrderInfo(map);
        return ResponseUtil.ResponseResult((isSave)?map.get("order_p_order_no"):"保存失败");
	}
	
	//通过订单号获取所有订单信息
	@RequestMapping("/getOrderInfoForTemp")
	public Map getOrderInfoForTemp(HttpServletRequest request) throws IOException, ServiceException  {  
		Map<String, String> map=RequestUtil.getRequestAllParam(request);
		JSONObject object = orderCreateService.getOrderInfoForTemp(map);
        return ResponseUtil.ResponseResult(object);
	} 
	//检查模版和订单号准确性
	@RequestMapping("/checkTempAndOrderNo")
	public Map checkTempAndOrderNo(HttpServletRequest request) throws IOException, ServiceException  {  
		Map<String, Object> map=RequestUtil.getRequestAllParam(request);
		int total = orderCreateService.checkTempAndOrderNo(map);
        return ResponseUtil.ResponseResult(total);
	}

	//更新订单 --审核订单使用
	@RequestMapping("/updateAudit")
	@ResponseBody
	public Map updateAudit(HttpServletRequest request) throws ServiceException {
		Map<String,String> map=RequestUtil.getRequestAllParam(request);
		/**
		 * 校验当前是否有人操作操作的人是本人的话 可以继续 不是本人提示
		 */
		map.put("orderNo", map.get("order_p_order_no"));
		chekCurrentOrderOperater(map);
		int total = orderCreateService.updateAudit(map);
        return ResponseUtil.ResponseResult(total);
	}
	//制定订单select下拉动态添加option
	@RequestMapping("/selectOnlineByType")
	@ResponseBody
	public Map selectOnlineByType(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.selectOnlineByType(map));
	}
	//通过条件获取生产订单主表数据
	@RequestMapping("/getOrderInfoByParam")
	@ResponseBody
	public Map getOrderInfoByParam(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.getOrderInfoByParam(map));
	}
	
	//通过条件获取模版数据
	@RequestMapping("/getTemplateList")
	@ResponseBody
	public DatatablesViewPageBean getTemplateList(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
        return orderInfoTemplateService.getTemplateList(map);
	}
	@RequestMapping("/updateTemplateById")
	public Map updateTemplateById(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		orderInfoTemplateService.updateTemplateById(map);
        return ResponseUtil.ResponseResult(null);
	}
	@RequestMapping("/deleteOrderInfoPrimary")
	public Map deleteOrderInfoPrimary(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		orderCreateService.deleteOrderInfoPrimary(map);
        return ResponseUtil.ResponseResult(null);
	}
	@RequestMapping("/operateLog")
	public Map operateLog(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
		orderCreateService.operateLog(map);
        return ResponseUtil.ResponseResult(null);
	}
	/**
	 * 通过业务单号
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	@RequestMapping("/getOrderNoByBussNo")
	public Map getOrderNoByBussNo(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.getOrderNoByBussNo(map));
	}
	/**
	 * 获取物料工艺列表
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	@RequestMapping("/getArtsList")
	public Map getArtsList(HttpServletRequest request) throws IOException, ServiceException  {  
		Map map=RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(orderCreateService.getArtsList(map));
	}
	/**
	 * 获取订单申请中的信息
	 */
	@RequestMapping("/getMyApplyInfo")
	public Map getMyApplyInfo(HttpServletRequest request,String orderNo) {
		Map map=RequestUtil.getRequestAllParam(request);
		return ResponseUtil.ResponseResult(orderCreateService.getMyApplyInfo(orderNo));
	}
	/**
	 * 多人编辑模式下校验当前操作人是否为订单控制人
	 * @param map
	 */
	public void chekCurrentOrderOperater(Map<String,String> map) {
		Object object = RedisCache.getDataFromRedis("isOperate-"+map.get("loginCompany")+"-"+map.get("orderNo"));
    	if(object!=null) {//有人操作该订单则返回操作人信息
    		JSONObject jsonObject = (JSONObject)JSON.parse(object.toString());
    		if(jsonObject.getString("loginUserName").equals(map.get("loginUserName"))) {//避免是自己操作出现误判
    			//是自己操作继续接下去流程
    		}else {
    			throw new ServiceException("当前订单已经由 ["+jsonObject.getString("loginUserName")+"] 操作中,暂时无法继续当前操作,请等待");
    		}
    		
    	}
	}
	/**
	 * 批量保存设备订单
	 */
	@RequestMapping("/insertOrderBatchForDevice")
	public Map insertOrderBatchForDevice(HttpServletRequest request) {
		Map map=RequestUtil.getRequestAllParam(request);
		orderCreateService.insertOrderBatchForDevice(map);
		return ResponseUtil.ResponseResult("保存成功");
	}
	/**
	 * 批量保存设备订单
	 */
	@RequestMapping("/updateOrderBatchForDevice")
	public Map updateOrderBatchForDevice(HttpServletRequest request) {
		Map map=RequestUtil.getRequestAllParam(request);
		orderCreateService.updateOrderBatchForDevice(map);
		return ResponseUtil.ResponseResult("修改成功");
	}
	/**获取订单列表**/
	@RequestMapping("/selectOrderBatchForDevice")
	@ResponseBody
	public DatatablesViewPageBean selectOrderBatchForDevice(HttpServletRequest request) throws ServiceException {
		Map map=RequestUtil.getRequestAllParam(request);
		return orderCreateService.selectOrderBatchForDevice(map);
	}
}
